<?php
namespace Weigw\Controller;
use Think\Controller;
class BaseController extends Controller{
    /*
     * 生成签名的算法
     */
    public function getsignature(){
        $jsapi_ticket = $this->getjsapi_ticket();
        $noncestr = $this->getnoncestr();
        $timestamp = time();
        $url =$_SERVER["REQUEST_SCHEME"]."://".$_SERVER["SERVER_NAME"]. __SELF__;

       $str ="jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $signature = sha1($str);
        return array("noncestr"=>$noncestr,"timestamp"=>$timestamp,"signature"=>$signature,"url"=>$url);
    }

    /*
     * 生产随机数的方法
     */
    public function getnoncestr($length=16){
        $arr =array_merge(range("a","z"),range(0,9));//快速生成数组
        $noncestr="";
        shuffle($arr);//将数组的顺序打乱
        $arr_length = count($arr);
        for($i=1;$i<=$length;$i++){
            $index= rand(0,$arr_length-1);//随机生成的数组下标
            $noncestr.=$arr[$index];
        }
        return $noncestr;
    }


    /*
     * 获取jsapi_ticket
     */
    public function getjsapi_ticket(){
        $access_token = $this->getaccess_token();
        $url ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
        $res = $this->surl($url);
        if($res["ticket"]) return $res["ticket"];
        else return null;
    }

    /*
     * @param string $url   接口地址
     * @param string $fields post请求传递的参数
     */
    public function curl($url,$fields=""){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_ENCODING,"utf8");

        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);

        curl_setopt($ch,CURL_TIMEOUT, 30);

        //设置是否是post请求
        if(!empty($fields)){
            curl_setopt($ch,CURLOPT_POST,1); //只要值不为0都是post请求
            curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
        }

        $res =json_decode(curl_exec($ch),true);


        curl_close($ch);
        return $res;

    }

    /*
     * 获取access_token
     */
    public function getaccess_token(){
        //缓存:文件缓存  内存缓存
        $access_token = "";
        $access_path = "access_token.txt";
        if(is_file($access_path) && file_get_contents($access_path) && filemtime($access_path)+7200>time()){
            $access_token =file_get_contents($access_path);
        }else {
            $appid = C("APPID");
            $secret = C("APPSECRET");
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $res = $this->curl($url);
            $access_token = $res["access_token"];
            file_put_contents($access_path, $access_token);
        }
        return $access_token;
    }
}